package com.cyx.service.impl;

import com.cyx.exception.ClassHasStudentsException;
import com.cyx.mapper.ClazzMapper;
import com.cyx.mapper.StudentMapper;
import com.cyx.pojo.Clazz;
import com.cyx.pojo.ClazzQueryParam;
import com.cyx.pojo.PageResult;
import com.cyx.service.ClazzService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        // 1、设置分页参数 (PageHelper)
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        // 2、执行查询
        List<Clazz> clazzList = clazzMapper.list(clazzQueryParam);
        // 3、解析查询结果 并封装
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult<Clazz>(p.getTotal(),p.getResult());
    }

    @Override
    @Transactional
    public void deleteClazzById(Integer id) {
        // 查询要删除班级是否有学生
        if(studentMapper.countByClazzId(id) > 0){
            throw new ClassHasStudentsException("对不起, 该班级下有学生, 不能直接删除");
        }
        clazzMapper.deleteClazzById(id);
    }

    @Override
    public void add(Clazz clazz) {
        // 设置时间
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.add(clazz);
    }
    @Override
    public Clazz getInfoById(Integer id) {
        return clazzMapper.getInfoById(id);
    }
    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateById(clazz);
    }
    @Override
    public List<Clazz> findAll() {
        return clazzMapper.findAll();
    }

}
